package platform.txclfa.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import platform.common.CommonInfo;
import platform.txclfa.util.MsgUtil;
import platform.xtfw.client.MyChannelInitializer;

public class NettyClient {
    public static void main(String[] args) {
        new platform.xtfw.client.NettyClient().connect(CommonInfo.url,CommonInfo.port);
    }

    public void connect(String url, int port) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new MyChannelInitializer());
            ChannelFuture f = b.connect(url, port).sync();
            System.out.println("启动成功");

            // 测试消息，分别方demo1，demo2，demo3
            f.channel().writeAndFlush(MsgUtil.buildMsgDemo01(f.channel().id().toString(),"消息体01"));
            f.channel().writeAndFlush(MsgUtil.buildMsgDemo02(f.channel().id().toString(),"消息体02"));
            f.channel().writeAndFlush(MsgUtil.buildMsgDemo03(f.channel().id().toString(),"消息体03"));


            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
